<template>
  <div :class=" propGoodsId ? '' : 'app-container'">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="goodsId" v-if="!propGoodsId">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入商品编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="串号" prop="goodsSn" v-if="!propGoodsId">
        <el-input
          v-model="queryParams.goodsSn"
          placeholder="请输入串号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机型" prop="goodsName" v-if="!propGoodsId">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入机型"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="暂借人" prop="loanName">
        <el-input
          v-model="queryParams.loanName"
          placeholder="请输入暂借人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="借出中" :value="1" />
          <el-option label="结束" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['recovery:loan:add']"
          v-if="!propGoodsId"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['recovery:loan:export']"
          v-if="!propGoodsId"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="loanList" border :row-class-name="setRowClassName">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="商品编码" align="center" prop="goodsId" width="180">
        <template v-slot="scope">
          <span @click="openDetailWindow(scope.row)" class="link-type">{{scope.row.goodsId}}</span>
        </template>
      </el-table-column>
      <el-table-column label="机型" align="center" prop="goodsName" show-overflow-tooltip />
      <el-table-column label="串号" align="center" prop="goodsSn" show-overflow-tooltip />
      <el-table-column label="暂借人" align="center" prop="loanName" width="80" show-overflow-tooltip />
      <el-table-column label="价格" align="center" prop="loanPrice" width="80" />
      <el-table-column label="电话" align="center" prop="mobile" width="130" />
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="140">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status === 1">借出中</el-tag>
          <el-tag type="info" v-else>结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template v-slot="scope">
          <el-button v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateByStatus(scope.row)"
            v-hasPermi="['recovery:loan:edit']"
          >结束</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="商品详情" :visible.sync="detailOpen" width="500px" append-to-body>
      <el-form ref="goodsInfo" v-if="goodsInfo != null" label-width="80px">
        <el-form-item label="商品编码: ">{{goodsInfo.goodsId}}</el-form-item>
        <el-form-item label="商品名称: ">{{goodsInfo.goodsName}}</el-form-item>
        <el-form-item label="串号: ">{{goodsInfo.goodsSn}}</el-form-item>
        <el-form-item label="规格: ">{{goodsInfo.printing}}</el-form-item>
        <el-form-item label="仓库: ">{{stockFormatter(goodsInfo.stockId)}}</el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="修改信息" :visible.sync="updateOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="商品编码" prop="goodsId">
          <el-input v-model="form.goodsId" :disabled="true" />
        </el-form-item>
        <el-form-item label="串号" prop="goodsSn">
          <el-input v-model="form.goodsSn" :disabled="true" />
        </el-form-item>
        <el-form-item label="暂借人" prop="loanName">
          <el-input v-model="form.loanName" :disabled="true" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateSubmit">确 定</el-button>
        <el-button @click="updateCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改暂借登记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="goodsId">
              <el-input v-model="form.goodsId" placeholder="请输入商品编码"
                        style="width: 80%" @keyup.enter.native="getGoodsChange" :disabled="form.loanId != null" />
            </el-form-item>
            <el-form-item label="串号" prop="goodsSn">
              <el-input v-model="form.goodsSn" placeholder="请输入串号"
                        style="width: 80%" @keyup.enter.native="getGoodsChange" :disabled="form.loanId != null" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="暂借人" prop="loanName">
              <el-input v-model="form.loanName" placeholder="请输入暂借人"
                        style="width: 80%" @keyup.enter.native="getGoodsChange" :disabled="form.loanId != null" />
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入电话"
                        style="width: 80%" @keyup.enter.native="getGoodsChange" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注"
                        style="width: 80%" @keyup.enter.native="getGoodsChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table v-loading="loading" :data="addLoanList" border>
        <el-table-column label="商品编码" align="center" prop="goodsId" width="180" />
        <el-table-column label="商品名称" align="center" prop="goodsName" width="120" show-overflow-tooltip />
        <el-table-column label="串号" align="center" prop="goodsSn" width="120" show-overflow-tooltip />
        <el-table-column label="暂借人" align="center" prop="loanName" width="80" />
        <el-table-column label="电话" align="center" prop="mobile" />
        <el-table-column label="价格" align="center" prop="loanPrice" width="180">
          <template v-slot="scope">
            <el-input type="number" v-model="scope.row.loanPrice" :min="0" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-remove"
              @click="handleCancel(scope.row)"
              v-hasPermi="['recovery:loan:remove']"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLoan, delLoan, exportLoan, getGoodsLoan, addLoanList, updateLoan, getLoan } from "@/api/recovery/loan";
import {getGoods} from "@/api/recovery/goods"
import {listStock} from "@/api/recovery/stock"

export default {
  name: "Loan",
  components: {
  },
  props: {
    propGoodsId: {type: String}
  },
  watch: {
    propGoodsId(val) {
      this.queryParams.goodsId = val;
      this.getList()
    },
  },
  data() {
    return {
      updateOpen: false,
      //仓库列表
      stockList: [],
      //详情开关
      detailOpen: false,
      //商品详情
      goodsInfo: null,
      //要新增的暂借登记
      addLoanList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 暂借登记表格数据
      loanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: this.propGoodsId,
        loanName: null,
        status: null,
        goodsSn: null,
        goodsName: null,
        createBy: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    listStock().then(resp => {
      this.stockList = resp.rows;
    })
  },
  methods: {
    updateCancel() {
      this.updateOpen = false;
    },
    /** 仓库格式 */
    stockFormatter(stockId) {
      for (let i = 0; i < this.stockList.length; i++) {
        if(stockId === this.stockList[i].stockId) {
          return this.stockList[i].stockName;
        }
      }
    },
    //根据指定数据，设置行背景色
    setRowClassName(data) {
      const oneDay = 1000 * 60 * 60 * 24; //一天的时间
      let newDate = new Date();
      let longTime = newDate.getTime() - new Date(data.row.createTime).getTime();
      let day = longTime / oneDay;
      if(day >= 3 && data.row.status === 1) {
        return 'bg_red';
      }
    },
    /** 打开详情框 */
    openDetailWindow(row) {
      getGoods(row.goodsId).then(resp => {
        this.goodsInfo = resp.data;
        this.detailOpen = true;
      })
    },
    /**结束事件*/
    handleUpdateByStatus(row) {
      this.$confirm("确定结束借出状态了吗？", "警告", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        row.status = 2;
        return updateLoan(row);
      }).then(resp => {
        this.msgSuccess("操作成功！");
        this.getList();
      })
    },
    // 暂借取消
    handleCancel(row) {
      for(let i = 0; i < this.addLoanList.length; i++) {
        if(row.goodsId === this.addLoanList[i].goodsId) {
          this.addLoanList.splice(i, 1);
          break;
        }
      }
    },
    //获取合格暂借商品信息
    getGoodsChange(e) {
      if(this.form.goodsId == null && this.form.goodsSn == null) {
        return ;
      }
      if(this.form.goodsId === '' && this.form.goodsSn === '') {
        return ;
      }
      if (this.form.loanName == null) {
        this.msgError("请先输入暂借人！")
        return;
      }
      let data = {
        goodsSn: this.form.goodsSn,
        goodsId: this.form.goodsId
      }
      getGoodsLoan(data).then(resp => {
        for(let i = 0; i < this.addLoanList.length; i++) {
          if(resp.data.goodsId === this.addLoanList[i].goodsId) {
            this.msgError("该数据已经存在列表当中！")
            return
          }
        }
        let loan = {
          goodsName: resp.data.goodsName,
          goodsSn: resp.data.goodsSn,
          goodsId: resp.data.goodsId,
          loanPrice: resp.data.costPrice,
          loanName: this.form.loanName,
          goodsStep: resp.data.goodsStep,
          remark: this.form.remark,
          mobile: this.form.mobile
        }
        this.addLoanList.unshift(loan);
        this.form.goodsSn = null;
        this.form.goodsId = null;
      })
    },
    /** 查询暂借登记列表 */
    getList() {
      this.loading = true;
      listLoan(this.queryParams).then(response => {
        this.loanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        loanId: null,
        goodsId: null,
        goodsSn: null,
        loanName: null,
        remark: null,
        mobile: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.loanId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加暂借登记";
    },
    /** 修改按钮*/
    handleUpdate(row) {
      this.reset();
      getLoan(row.loanId).then(resp => {
          this.form = resp.data;
          this.updateOpen = true;
          this.title = "修改暂借登记";
      })
    },
    updateSubmit() {
      updateLoan(this.form).then(resp => {
        this.msgSuccess("操作成功！")
        this.getList();
        this.reset();
        this.updateOpen = false;
      })
    },
    /** 提交按钮 */
    submitForm() {
      if(this.addLoanList.length === 0) {
        this.msgError("没有暂借的商品吗？")
        return;
      }
      addLoanList(this.addLoanList).then(resp => {
        this.msgSuccess("操作成功！")
        this.getList();
        this.addLoanList = [];
      })
      this.open = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const loanIds = row.loanId || this.ids;
      this.$confirm('是否确认删除暂借登记编号为"' + loanIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLoan(loanIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有暂借登记数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportLoan(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>

<style>
.el-table .bg_red {
  color: red;
}
</style>
